package com.opg.uop.manage.system.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.opg.uop.manage.base.UOPRestApiException;
import com.opg.uop.manage.base.UOPRestApiResponse;
import com.opg.uop.manage.base.UOPServiceResponse;

@Controller
@RequestMapping("/menus")
public class MenuController {
	
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private RestTemplate restTemplate;
	
	@RequestMapping("/menuList")
	@ResponseBody
	public UOPRestApiResponse getMenuList(@RequestParam("state") String state,@RequestParam("isleaf") String isleaf){
		UOPRestApiResponse uar = new UOPRestApiResponse();
		try {
			UOPServiceResponse uopServiceResponse = restTemplate
					.getForEntity("http://uop-system-server/menus?state="+state+"&isleaf="+isleaf, UOPServiceResponse.class).getBody();
			String code = uopServiceResponse.getMeta().get("code").toString();
			if (UOPServiceResponse.FAILED.equals(code)) {
				throw new UOPRestApiException(uopServiceResponse.getError().get("message").toString());
			} else {
				uar.setData(uopServiceResponse.getData());
			}
		} catch (Exception e) {
			throw new UOPRestApiException(e);
		}
		return uar;
	}
	
	@RequestMapping("/getSecondaryMenuList")
	@ResponseBody
	public UOPRestApiResponse getSecondaryMenuList(@RequestParam("menuId") String menuId){
		UOPRestApiResponse uar = new UOPRestApiResponse();
		try {
			UOPServiceResponse uopServiceResponse = restTemplate
					.getForEntity("http://uop-system-server/menus/getSecondaryMenu?userid=51&menuid="+menuId, UOPServiceResponse.class).getBody();
			String code = uopServiceResponse.getMeta().get("code").toString();
			if (UOPServiceResponse.FAILED.equals(code)) {
				throw new UOPRestApiException(uopServiceResponse.getError().get("message").toString());
			} else {
				uar.setData(uopServiceResponse.getData());
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			e.printStackTrace();
			throw new UOPRestApiException(e);
		}
		return uar;
	}
}
